package com.atguigu.cloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.atguigu.cloudalibaba.handler.CustomerBlockHandler;
import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException",fallback = "handleException2")
    public CommonResult byResource() {
        int i = 1/0;
        return new CommonResult(200,"OK",new Payment(2020L,"serial001"));
    }

    @GetMapping("/byUrl")
    @SentinelResource(value = "byUrl",blockHandler = "handleException")
    public CommonResult byUrl() {
        return new CommonResult(200,"OK",new Payment(2020L,"serial001"));
    }


    public CommonResult handleException(BlockException exception) {
        return new CommonResult(444,"进行了限流,进入blockHandler"+ exception.getClass().getCanonicalName());
    }

    public CommonResult handleException2(Throwable exception) {
        return new CommonResult(444,"接口异常，进行fallback,异常信息" + exception.getMessage());
    }

    //==================


    /**
     * 自定义通用的限流处理逻辑，
     blockHandlerClass = CustomerBlockHandler.class
     blockHandler = handleException
     上述配置：找CustomerBlockHandler类里的handleException方法进行兜底处理
     */
    /**
     * 自定义通用的限流处理逻辑
     */
    @GetMapping("/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException")
    public CommonResult customerBlockHandler() {
        return new CommonResult(200,"ok");
    }
}
